<template>
  <view class="edit-container">
    <!-- 表单字段分组 -->
    <view class="form-group">
      <input 
        v-model.trim="form.name" 
        placeholder="收货人姓名" 
        maxlength="20"
      />
    </view>
    
    <view class="form-group">
      <input 
        v-model.trim="form.mobile" 
        placeholder="联系电话" 
        type="number"
        maxlength="11"
      />
    </view>
    
    <view class="form-group">
      <hy-provinces 
        :provinceId="form.provinceId"
        :cityId="form.cityId"
        :districtId="form.districtId"
        @updateAddress="handleAddressChange"
      />
    </view>
    
    <view class="form-group">
      <textarea 
        v-model.trim="form.detail" 
        placeholder="详细地址（如街道、门牌号等）"
        maxlength="100"
      />
    </view>
    
    <view class="form-group checkbox">
  <label class="checkbox-label" @click="toggleDefault">
    <checkbox 
      :checked="form.isDefault == 1"
      color="#409eff"
      @click.stop="toggleDefault"
    />
    设为默认地址
  </label>
</view>
    
    <view class="button-group">
      <button 
        @click="handleSubmit"
        :disabled="isSubmitting"
      >
        {{ isSubmitting ? '保存中...' : '保存' }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getAddressInfoAPI, editAddressAPI } from "@/api/address"
import HyProvinces from "@/components/HyProvinces.vue";
import {showError, showSuccess, showWarning} from '@/utils/feedback'
// 表单初始状态
const getInitialForm = () => ({
  id: null,
  name: "",
  mobile: "",
  detail: "",
  isDefault: '0',
  provinceId: null,
  cityId: null,
  districtId: null
});

const card_id = ref(null);

const form = ref(getInitialForm());

const isSubmitting = ref(false);

/**
 * 更新地址信息到表单中
 * @param {Object} address - 包含省市区ID的对象
 */
const handleAddressChange = (address) => {
  form.value = {
    ...form.value,
    ...address
  };
};

// 修改 isDefault 的值
const toggleDefault = () => {
  form.value.isDefault = form.value.isDefault == 1 ? 0 : 1;
};

// 获取地址详情
const fetchAddressInfo = async (id) => {
  try {
    const res = await getAddressInfoAPI(id);
    
    if (res.code == 200) {
      form.value = {
        ...form.value,
        ...res.data,
      };
    } else {
      showError(res.message);
    }
  } catch (error) {
    console.error("获取地址信息异常:", error);
    showError("网络异常，请稍后重试");
  }
};

// 表单验证
const validateForm = () => {
  const { name, mobile, detail, provinceId } = form.value;
  
  if (!name.trim()) {
    showWarning("请输入收货人姓名");
    return false;
  }
  
  if (!/^1[3-9]\d{9}$/.test(mobile)) {
    showWarning("请输入正确的手机号码");
    return false;
  }
  
  if (!provinceId || !detail.trim()) {
    showWarning("请填写完整的地址信息");
    return false;
  }
  
  return true;
};

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) return;

  isSubmitting.value = true;  
  try {
    const res = await editAddressAPI(
      form.value
    );
    
    if (res.code == 200) {
      showSuccess("保存成功");
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/address/index?card_id=${card_id.value}`
        });
      }, 1500);
    } else {
      showError(res.message);
    }
  } catch (error) {
    console.error("保存地址异常:", error);
    showError(error.message || "保存失败");
  } finally {
    isSubmitting.value = false;
  }
};

/**
 * 页面加载生命周期
 * 如果有地址 ID，则请求地址详情进行编辑
 */
onLoad((options) => {
  card_id.value = options.card_id;
  if (options.id) {
    fetchAddressInfo(options.id);
  }
});
</script>

<style scoped lang="scss">
.edit-container {
  padding: 20px;
  padding-bottom: 80px;
}

.form-group {
  background-color: #fff;
  padding: 16px;
  border-radius: 8px;
  
  input, textarea {
    font-size: 15px;
    padding: 12px;
    border: 1px solid #eee;
    border-radius: 6px;
    background-color: #f9f9f9;
  }
  textarea{
    width: auto;
  }
}

.checkbox {
  &-label {
    display: flex;
    align-items: center;
    font-size: 15px;
    
    checkbox {
      margin-right: 8px;
      transform: scale(1.1);
    }
  }
}

.button-group {
  margin-top: 20px;
  button {
    font-size: 16px;
    height: 48px;
    line-height: 48px;
    background-color: $color-primary;
    color: #fff;

    &[disabled] {
      opacity: 0.6;
    }
  }
}
</style>